/**
 * 
 */
package com.glela.common.aspect;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liujie
 *
 */
public class ActionFilter implements Filter {
	private String			encoding;
	private static Logger	logger	= LoggerFactory.getLogger(ActionFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		encoding = "UTF-8";
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding(encoding);
		String servletPath = ((HttpServletRequest) request).getServletPath();
		//支付宝、微信和易宝支付回调通知不处理
		///order/yeePayCallBack
		if (servletPath.startsWith("/order/yeePayCallBack") || servletPath.startsWith("/order/yeePayWebCallBack2") || servletPath.startsWith("/order/alipay" + "Notify") || servletPath.startsWith("/order/wechatPublic" + "Notify") || servletPath.startsWith("/order/yeePayNetServer" + "Notify") || servletPath.startsWith("/report/")) {
			chain.doFilter(request, response);
		} else {
			RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request);
			chain.doFilter(requestWrapper, response);
		}
	}

	@Override
	public void destroy() {
		encoding = null;
	}

	/**
	 * 请求装饰类（设置请求数据编码为UTF-8）
	 * @author zls
	 *
	 */
	class RequestWrapper extends HttpServletRequestWrapper {
		private String	encoding	= null;
		private String	payload		= null;

		public RequestWrapper(HttpServletRequest request) {
			super(request);
			encoding = request.getCharacterEncoding();
			StringBuilder stringBuilder = new StringBuilder();
			BufferedReader bufferedReader = null;
			try {
				bufferedReader = this.getRequest().getReader();
				String val = null;
				while ((val = bufferedReader.readLine()) != null) {
					stringBuilder.append(val);
				}

				payload = stringBuilder.toString();
			} catch (IOException e) {
				logger.error("RequestWrapper异常", e);
			} finally {
				try {
					if (bufferedReader != null) {
						bufferedReader.close();
					}
				} catch (IOException e) {}
			}
		}

		@Override
		public BufferedReader getReader() throws IOException {
			return new BufferedReader(new InputStreamReader(getInputStream()));
		}

		@Override
		public ServletInputStream getInputStream() throws IOException {
			final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(StringUtils.isEmpty(encoding) ? payload.getBytes() : payload.getBytes(encoding));

			ServletInputStream inputStream = new ServletInputStream() {
				@Override
				public int read() throws IOException {
					return byteArrayInputStream.read();
				}

				@Override
				public boolean isFinished() {
					// TODO Auto-generated method stub
					return false;
				}

				@Override
				public boolean isReady() {
					// TODO Auto-generated method stub
					return false;
				}

				@Override
				public void setReadListener(ReadListener arg0) {
					// TODO Auto-generated method stub

				}
			};

			return inputStream;
		}

	}

}
